package com.mjh.aspect;


import com.mjh.annotaion.DataScope;
import com.mjh.model.BaseQuery;
import com.mjh.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Aspect
@Slf4j
public class DataScopeAspect {
    public static final String POINT_CUT = "@annotation(com.mjh.annotaion.DataScope)";
    @Around(POINT_CUT)
    public Object around(ProceedingJoinPoint joinPoint) {
       Object result = null;
       //获取目标方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解
        DataScope annotation = signature.getMethod().getAnnotation(DataScope.class);
        //获取注解的属性
        String tableAlias = annotation.tableAlias();
        String tableField = annotation.tableField();

        //获取当前登录用户的角色
        Set<String> roleList = AuthUtil.getSecurityUserRoleList();
        //判断当前登录用户是否管理员
       if(!roleList.contains("admin")){
          //当前用户角色不包含管理员角色，则进行数据权限控制
         // 获取目标方法的参数
            Object params = joinPoint.getArgs()[0];
            //将目标方法参数转换为BaseQuery参数对象
            BaseQuery baseQuery = (BaseQuery) params;
            //获取登录用户id
            Integer loginUserId = AuthUtil.getLoginUserId();
            //and tu.id = #{id}
            baseQuery.setFilterSQL("and " + tableAlias+ "." +tableField + " = " + loginUserId);
        }
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return result;
    }


}



